# from langchain_google_genai import GoogleGenerativeAI
from langchain_openai import ChatOpenAI  # 导入豆包 LLM 对应的类
from playwright.async_api import async_playwright
from datetime import datetime
import os
from llm.input_mapper_ai import input_mapper_ai
from time import sleep

async def highlight_inputs_and_get_metadata_async(url: str, llm: ChatOpenAI, data_to_fill: str):
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        page = await browser.new_page()
        await page.goto(url)

        input_elements = await page.query_selector_all("input, textarea, select")
        # Highlight inputs
        input_metadata = await page.evaluate("""(inputs) => {
            const metadata = [];

            inputs.forEach((el, index) => {
                const rect = el.getBoundingClientRect();

                el.style.border = "2px solid red";

                const label = document.createElement('div');
                label.innerText = index;
                label.style.position = 'absolute';
                label.style.left = `${rect.left + window.scrollX}px`;
                label.style.top = `${rect.top + window.scrollY - 20}px`;
                label.style.backgroundColor = 'red';
                label.style.color = 'white';
                label.style.fontSize = '14px';
                label.style.padding = '2px 5px';
                label.style.zIndex = 9999;
                label.className = 'ai-label-index';

                document.body.appendChild(label);

                metadata.push({
                    index: index,
                    tag: el.tagName.toLowerCase(),
                    type: el.type || null,
                    name: el.name || null,
                    id: el.id || null,
                    selector: el.outerHTML.slice(0, 100),
                });
            });

            return metadata;
        }""", input_elements)

        
        screenshot_bytes = await page.screenshot(full_page=True)
        response = input_mapper_ai(screenshot_bytes, llm, data_to_fill)
        
        for index, value in response.items():
            # if value and (input_metadata[int(index)]["type"] in ["text", "email", "password", "number", "textarea"] or input_metadata[int(index)]["tag"] == "textarea"):
            #     await input_elements[int(index)].fill(value)
            # print(f"Checkbox field {index}: {value}")
            try:
                idx = int(index)
                # 检查索引是否在有效范围内
                if idx < len(input_metadata) and value:
                    if (input_metadata[idx]["type"] in ["text", "email", "password", "number", "textarea"] 
                        or input_metadata[idx]["tag"] == "textarea"):
                        await input_elements[idx].fill(value)
                else:
                    print(f"索引 {idx} 超出范围或值为空，跳过填充操作")
            except ValueError:
                print(f"无法将 {index} 转换为整数，跳过此条目")

            print(f"Checkbox field {index}: {value}")


        
        await page.wait_for_timeout(5000)
        current_date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        curdir = os.getcwd()
        screenshot_path = f"screenshot_{current_date}.png"
        full_screenshot_path = os.path.join(curdir, "screenshots", screenshot_path)
       
        await page.screenshot(path=full_screenshot_path, full_page=True)
        print("Response from input_mapper_ai:", response)
        # 注释或删除关闭浏览器的代码
        # await browser.close()
        sleep(300)
        return screenshot_bytes